package c18类加载和反射;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class s10自定义ClassLoader extends ClassLoader {
	private String path;
	private String classLoaderName;

	public s10自定义ClassLoader(String path, String classLoaderName) {
		this.path = path;
		this.classLoaderName = classLoaderName;
	}

	/**
	 * 用于寻找类文件, 并转换成 class 返回
	 *
	 * @param name
	 * @return java.lang.Class
	 * @author Yuanwl
	 * @date 2019-03-20 12:35:26
	 * @version v1.0.0
	 */
	@Override
	public Class findClass(String name) {
		byte[] b = loadClassData(name);
		return defineClass(name, b, 0, b.length);
	}

	/**
	 * 用于加载类文件, 转换成字节数组
	 *
	 * @param name
	 * @return byte[]
	 * @author Yuanwl
	 * @date 2019-03-20 12:36:12
	 * @version v1.0.0
	 */
	private byte[] loadClassData(String name) {
		name = path + "/" + name + ".class";
		InputStream in = null;
		ByteArrayOutputStream out = null;
		try {
			in = new FileInputStream(new File(name));
			out = new ByteArrayOutputStream();
			int i = 0;
			while ((i = in.read()) != -1) {
				out.write(i);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return out.toByteArray();
	}
}
